package com.health.auth.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.health.api.client.UserClient;
import com.health.auth.service.LoginService;
import com.health.common.common.ErrorCode;
import com.health.common.exception.BusinessException;
import com.health.common.model.user.LoginUser;
import com.health.common.service.util.WeBASEUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


/**
 * 用户服务实现
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    /**
     * 盐值，混淆密码
     */
    public static final String SALT = "zhexueqi";


    @Resource
    private UserClient userClient;


    @Resource
    private WeBASEUtils weBASEUtils;


    @Override
    public LoginUser userLogin(String userAccount, String userPassword, Integer userRole, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        if (userRole == null || userRole < 1 || userRole > 10)  {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        LoginUser loginUser = userClient.getUserInfoByUserAccountAndUserPassword(userAccount, encryptPassword, userRole);
        if (loginUser ==null)
        {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        StpUtil.login(loginUser.getId());
        //返回LoginUser
        return loginUser;
    }


}
